package cn.cxy.demo

import android.os.AsyncTask
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_main.contentTv
import kotlinx.android.synthetic.main.activity_main2.*
import java.net.URL

class MainActivity2 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        queryData()
    }

    private fun queryData() {
        AsyncTask1().execute()
    }

    internal inner class AsyncTask1 :
        AsyncTask<String?, Void?, String>() {
        override fun onPreExecute() {
            super.onPreExecute()
        }

        override fun onPostExecute(info: String) {
            super.onPostExecute(info)
            val (id, name) = Gson().fromJson(info, Task::class.java)
            contentTv.text = name
            queryData2()
        }

        override fun doInBackground(vararg params: String?): String {
            val url = "https://gitee.com/cxyzy1/AndroidAsyncTaskDemo/raw/master/data.json"
            return getInfoByUrl(URL(url))
        }
    }

    private fun queryData2() {
        AsyncTask2().execute()
    }

    internal inner class AsyncTask2 :
        AsyncTask<String?, Void?, String>() {
        override fun onPreExecute() {
            super.onPreExecute()
        }

        override fun onPostExecute(info: String) {
            super.onPostExecute(info)
            val (id, name) = Gson().fromJson(info, Task::class.java)
            contentTv2.text = name
        }

        override fun doInBackground(vararg params: String?): String {
            val url = "https://gitee.com/cxyzy1/AndroidAsyncTaskDemo/raw/master/data2.json"
            return getInfoByUrl(URL(url))
        }
    }
}